From f74523c96a890529544e9dec6df7fcc1827cee48 Mon Sep 17 00:00:00 2001 From: lonkaars Date: Tue, 30 Mar 2021 11:34:25 +0200 Subject: chapter heading parsing with hierarchy stuffs --- pages/post/[id].tsx | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) (limited to 'pages/post/[id].tsx') diff --git a/pages/post/[id].tsx b/pages/post/[id].tsx index 4f3050a..890fb4f 100644 --- a/pages/post/[id].tsx +++ b/pages/post/[id].tsx @@ -53,7 +53,7 @@ var parseTag = { "date": (val: string) => new Date(val).toDateString(), } -function parseMeta(file: Array) { +function parseMeta(file: Array): ArticleMeta { var meta: ArticleMeta = {}; file.forEach(line => { @@ -67,10 +67,48 @@ function parseMeta(file: Array) { return meta; } +var headingLevel = (input: string) => input?.match(/^[#]+/)[0]?.length || 0; +function parseToCRecursive(headings: Array): Array { + interface WIPchapter extends chapter { + unparsedChildren?: Array; + } + var children: Array = [] + + var lowestLevel = headingLevel(headings[0]); + var currentChildIndex = -1; + for (var i in headings) { + var localLevel = headingLevel(headings[i]); + if (localLevel == lowestLevel) { + children.push({ + name: headings[i].match(/^[#]+\s+(.+)/)[1], + unparsedChildren: [], + }); + currentChildIndex += 1; + } else { + children[currentChildIndex].unparsedChildren.push(headings[i]) + } + } + + children.map(child => { + child.children = parseToCRecursive(child.unparsedChildren) + delete child.unparsedChildren; + + return child + }) + + return children as Array; +} + +function parseToC(file: Array): Array { + var chapterStrings = file.filter(line => line.startsWith("#")); + console.log(parseToCRecursive(chapterStrings)) + return parseToCRecursive(chapterStrings); +} + function preprocessor(fileContent: string) { var fileAsArr = fileContent.split("\n"); var meta = parseMeta(fileAsArr); - + meta.chapters = parseToC(fileAsArr); var result = fileAsArr.join("\n").trim() return { meta, result } } -- cgit v1.2.3